package com.coldlz.mmp.app;

import com.coldlz.mmp.pojo.HttpRecord;
import com.coldlz.mmp.pojo.TemplatePublisher;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

import java.util.concurrent.SubmissionPublisher;

@Configuration
public class AppConfig implements ApplicationContextAware {

    private ApplicationContext applicationContext;


    @PostConstruct
    public void init() {
        System.out.println(applicationContext.getApplicationName());
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Bean
    public TemplatePublisher<HttpRecord> templatePublisher() {
        SubmissionPublisher<HttpRecord> submissionPublisher = new SubmissionPublisher<>();
        return new TemplatePublisher<>(submissionPublisher);
    }

    @Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.setAllowCredentials(false);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config); // 对所有接口都生效
        return new CorsWebFilter(source);
    }
}
